import 'dart:async';

///多任务
///any 返回最先完成的Future
///wait 等待所有Future完成，收集所有Future的返回结果
///doWhile 根据条件完成Future
///forEach 遍历一个Future集合
void main() {
  // testAny();
  // testWait();
  // testWhile();
  testForEach();
}

void testAny(){
  print("start");
  Future.any([
    Future.delayed(Duration(seconds: 1)).then((value) => 3),
    Future.delayed(Duration(seconds: 1)).then((value) => 2),
    Future.delayed(Duration(seconds: 1)).then((value) => 1),
  ]).then((value) => print("最快返回结果：$value"));
  print("end");
}

void testWait(){
  print("start");
  Future.wait([
    Future.delayed(Duration(seconds: 4)).then((value) {
      print("task 1");
      return "1";
    } ),
    Future.delayed(Duration(seconds: 1)).then((value) {
      print("task 2");
      return 2;
    } ),
    Future.delayed(Duration(seconds: 2)).then((value) {
      print("task 3");
      return 3;
    } ),
  ]).then((value) => print("最快返回结果：$value"));
  print("end");
}


void testWhile(){
  print("start");
  var i = 0;
  Future.doWhile((){
    i++;
    // print("doWhile:$i");
    // return i < 6;

    return Future.delayed(Duration(seconds: 1),(){
      print("doWhile:$i");
      return i < 6;
    });

  });
  print("end");
}


void testForEach(){
  print("start");
  var i = 0;
  Future.forEach([1,2,3], (element) => Future.delayed(Duration(seconds: 2),(){
    print("element:$element");
  }));
  print("end");
}